import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Inject
} from '@nestjs/common'
import { WinstonLogger, WINSTON_MODULE_LOGGER } from '@ttou/nest-winston'
import { tap } from 'rxjs/operators'
import { Observable } from 'rxjs'
import { IRequest } from '@/common/interfaces'

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  constructor(
    @Inject(WINSTON_MODULE_LOGGER)
    private logger: WinstonLogger
  ) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.switchToHttp().getRequest<IRequest>()
    const controller = context.getClass().name
    const handler = context.getHandler().name

    const msg = `${controller} - ${handler} - ${req.method.toUpperCase()} - ${
      req.url
    }`
    const now = Date.now()

    this.logger.log(`-> ${msg}`, LoggingInterceptor.name)

    return next.handle().pipe(
      tap(() => {
        const time = `+${Date.now() - now}ms`

        this.logger.log(`<- ${msg} ${time}`, LoggingInterceptor.name)
      })
    )
  }
}
